<template>
  <div class="admin-page-content">
    <div class="has-top-from-bottom">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="用户名：">
          <el-input placeholder="支持模糊搜索" clearable v-model="query.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input placeholder="支持模糊搜索" clearable v-model="query.realname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left:20px;" type="primary" icon="el-icon-search" @click.native="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-btn-box">
      <el-button type="primary" size="small" @click.native="dialogVisible=true">新增用户</el-button>
      <el-button type="primary" size="small" @click.native="batchDeletion">批量删除</el-button>
      <el-button type="primary" size="small" @click.native="batchEnable">启用</el-button>
      <el-button type="primary" size="small" @click.native="batchDisable">停用</el-button>
    </div>
    <el-table v-loading="loading" :data="data" style="width: 100%;" border size="small" ref="userTable">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="realname"></el-table-column>
      <el-table-column label="角色" prop="roleId">
        <template slot-scope="scope">
          <el-tag type="success" size="mini" v-if="scope.row.roleId === '1'">超级管理员</el-tag>
          <el-tag type="warning" size="mini" v-if="scope.row.roleId === '2'">运维人员</el-tag>
          <el-tag type="danger" size="mini" v-if="scope.row.roleId === '3'">使用者</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="Token" prop="token"></el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.status === 0" effect="plain">启用</el-tag>
          <el-tag type="danger" size="mini" v-if="scope.row.status === 1" effect="plain">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="icon-table edit-icon" @click="editFrom(scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="scope.row.roleId !== '1'">
            <i class="icon-table delete-icon" @click="deleteUser(scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="停用" placement="top" v-if="scope.row.status === 0">
            <i class="icon-table icon-tingyong" @click="updateUserStatus(scope.row, 1)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="启用" placement="top" v-if="scope.row.status === 1">
            <i class="icon-table icon-qiyong" @click="updateUserStatus(scope.row, 0)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="重置密码" placement="top">
            <i class="icon-table icon-pass" @click="restUserPassword(scope.row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination background @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="query.pageNumber"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="100"
      layout="sizes, prev, pager, next"
      :total="total"></el-pagination>
      <span class="span-pagination">共{{Math.ceil(total/query.pageSize)}}页,{{total}}条数据</span>
    </div>

    <el-dialog :title="inputFrom.id ? '编辑用户' : '新增用户'" :close-on-press-escape="false"
      :close-on-click-modal="false" :visible.sync="dialogVisible">
      <div class="adduser-model">
        <el-form :model="inputFrom" :rules="inputRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <div class="left-from-item">
            <div class="box-body">
              <el-form-item label="用户名:" prop="username">
                <el-input v-model="inputFrom.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item label="密码:" prop="password" v-if="!inputFrom.id">
                <el-input type="password" v-model="inputFrom.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="姓名:" prop="realname">
                <el-input v-model="inputFrom.realname" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item label="手机号:" prop="mobile">
                <el-input type="tel" v-model="inputFrom.mobile" placeholder="请输入手机号"></el-input>
              </el-form-item>
              <el-form-item label="邮箱:" prop="email">
                <el-input v-model="inputFrom.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="角色:" prop="email">
                <el-select v-model="inputFrom.roleId" placeholder="请选择角色"
                  style="width:100%" :disabled="inputFrom.id?true:false" @change="changeRoles">
                  <template v-for="(item,key) in roleList">
                  <el-option v-if="item.id !== '1'" :key="key" :value="item.id" :label="item.name"></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="状态:" prop="status">
                <el-select v-model="inputFrom.status" placeholder="请选择状态" style="width:100%">
                  <el-option :value="0" label="启用"></el-option>
                  <el-option :value="1" label="停用"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="right-from-item">
            <el-form-item label="用户权限" prop="menus" class="right-from-box">
             <div class="select-rould-box">
               <el-tree :data="TreeMenu" show-checkbox  :default-expand-all="true"
                node-key="id" :props="{children:'childs',label: 'name'}" ref="tree"></el-tree>
             </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click.native="cancelSubmit">取消</el-button>
        <el-button type="primary" @click.native="submitFrom('ruleForm')">提交</el-button>
      </div>  
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, getUserInfo, getRulesList, getTreeMenu,
  addUser, updateUser, deleteUser, restUserPass, batchDeleteUser,
  batchEnableUser,batchDisableUser } from '@/api/admin/user-manage'
const checkPhone = (rule, value, callback) => {
  const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
  if(!value || value === '') {
    return callback(new Error('手机号不能为空'))
  } else if(!reg.test(value)) {
    return callback(new Error('手机号格式错误'))
  } else {
    callback()
  }
}
export default {
  data() {
    return {
      query: {
        username: '',
        realname: '',
        pageNumber: 1,
        pageSize: 10
      },
      loading: true,
      total: 0,
      data: [],
      dialogVisible: false,
      roleList: [],
      TreeMenu: [],
      inputFrom: {
        username: '',
        realname: '',
        password: '',
        mobile: '',
        email: '',
        roleId: '',
        status: 0,
        menus: []
      },
      inputRules: {
        username: [ { required: true, message: '请输入用户名', trigger: 'blur' }],
        realname: [ { required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [ { required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [ { required: true, validator:checkPhone, trigger: 'blur'} ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur'},
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
        ],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        menus: [
          { required: true, message: '请选择菜单', trigger: 'change'},
          { type: 'array', message: '请至少选择一个菜单', trigger: 'change'}
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.initPageData();
    this.getUserList();
  },
  methods: {
    // 选择角色
    changeRoles(val) {
      if (val === '2') {
        let temp = this.TreeMenu.map(function(item){
          return item.id
        })
        this.$refs.tree.setCheckedKeys(temp)
      } else {
        this.$refs.tree.setCheckedKeys([])
      }
      
    },
    // 批量停用
    batchDisable() {
      const vm = this;
      let selectRow = vm.$refs.userTable.selection.map(function(item) {
        return item.id
      })
      if (!selectRow.length) {
        vm.$message.error('请选择用户');
        return
      }
      vm.$confirm(`批量停用用户之后，用户将都不可使用，请谨慎操作。`, `批量停用`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        batchDisableUser({ids:selectRow}).then((responese)=>{
          if(responese.code === '20000') {
            vm.$message.success('批量停用用户成功');
            vm.getUserList()
          }
        })
      })
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 批量启用
    batchEnable() {
      const vm = this;
      let selectRow = vm.$refs.userTable.selection.map(function(item) {
        return item.id
      })
      if (!selectRow.length) {
        vm.$message.error('请选择用户');
        return
      }
      vm.$confirm(`批量启用用户之后，用户将都可使用，请谨慎操作。`, `批量启用`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        batchEnableUser({ids:selectRow}).then((responese)=>{
          if(responese.code === '20000') {
            vm.$message.success('批量启用用户成功');
            vm.getUserList()
          }
        })
      })
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 批量删除
    batchDeletion() {
      const vm = this;
      let selectRow = vm.$refs.userTable.selection.map(function(item) {
        return item.id
      })
      if (!selectRow.length) {
        vm.$message.error('请选择用户');
        return
      }
      vm.$confirm(`批量删除用户之后，用户将不可使用，请谨慎操作。`, `批量删除`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        batchDeleteUser({ids:selectRow}).then((responese)=>{
          if(responese.code === '20000') {
            vm.$message.success('批量删除用户成功');
            vm.getUserList()
          }
        })
      })
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 重置用户密码
    restUserPassword(row) {
      const vm = this;
      vm.$confirm(`重置用户密码将导致用户原密码不可用，请谨慎操作。`,'重置密码',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(()=>{
        restUserPass({id:row.id}).then((responese)=> {
          if(responese.code === '20000') {
            vm.$alert(`密码重置成功，新密码：${responese.data.password}`,`密码重置成功`,{
              confirmButtonText: '确定',
            })
          }
        })
      })
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 停用或者启用
    updateUserStatus(row,status) {
      const vm = this;
      let desc = status === 1 ? 
        '请确认是否停用用户，停用将导致用户不可使用，请谨慎操作。': 
        '请确认是否启用用户，启用后用户可使用相关权限，请谨慎操作。'
      vm.$confirm(desc,`${status === 1 ? '停用': '启用'}用户`,{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        if (status === 1) {
          batchDisableUser({ids:[row.id]}).then((responese)=>{
            if(responese.code === '20000') {
              vm.$message.success(`${status === 1 ? '停用': '启用'}用户成功`);
              vm.getUserList()
            }
          })
        } else {
          batchEnableUser({ids:[row.id]}).then((response)=>{
            if(response.code === '20000') {
              vm.$message.success(`${status === 1 ? '停用': '启用'}用户成功`);
              vm.getUserList()
            }
          })
        }
        // updateUser({id:row.id,status:status}).then((responese)=>{
        //   if(responese.code === '20000') {
        //     vm.$message.success(`${status === 1 ? '停用': '启用'}用户成功`);
        //     vm.getUserList()
        //   }
        // })
      })
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 删除用户
    deleteUser(row) {
      const vm = this;
      vm.$confirm('请确认是否删除用户，删除将导致用户不可使用，删除后不可恢复，请谨慎操作！','删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        deleteUser({id:row.id}).then((responese) => {
          if(responese.code === '20000') {
            vm.$message.success('删除成功');
            vm.getUserList()
          }
        })
      }).catch(() => {
        vm.$message.info('已取消删除')
      })
    },
    // 弹出修改
    async editFrom(row) {
      const vm = this;
      let responese = await getUserInfo({id:row.id})
      if (responese.code === '20000') {
        vm.inputFrom = {
          id: responese.data.id,
          username: responese.data.username,
          realname: responese.data.realname,
          // password: responese.data.username,
          mobile: responese.data.mobile,
          email: responese.data.email,
          roleId: responese.data.roleId,
          status: responese.data.status,
          menus: responese.data.menus,
        }
        let temp = []
        for (const item of responese.data.menus) {
          temp.push(item.menuId)
        }
        vm.dialogVisible = true
        setTimeout(()=>{
          vm.$refs.tree.setCheckedKeys(temp)
        },300)
      }
    },
    // 提交
    submitFrom(ruleFrom) {
      const vm = this;
      let selectMenu = vm.$refs.tree.getCheckedKeys()
      let temp = []
      for (const item of selectMenu) {
        temp.push({menuId:item})
      }
      vm.inputFrom.menus = temp
      vm.$refs[ruleFrom].validate((valid)=>{
        if (valid) {
          if (vm.inputFrom.id) {
            // 修改
            vm.updateOrAddUser(true)
          } else {
            // 新增
            vm.updateOrAddUser(false)
          }
        }
      })
    },
    async updateOrAddUser(val) {
      const vm = this;
      let responese;
      if (val) {
        responese = await updateUser(vm.inputFrom)
      } else {
        responese = await addUser(vm.inputFrom)
      }
      if (responese.code === '20000') {
        vm.$message.success('保存成功');
        vm.inputFrom = vm.$options.data().inputFrom
        vm.dialogVisible = false
        vm.getUserList()
      }
    },
    // 取消提交
    cancelSubmit() {
      this.inputFrom = this.$options.data().inputFrom;
      this.dialogVisible = false
    },
    async initPageData() {
      const vm = this;
      let rules_res = await getRulesList({pageNumber:1, pageSize:10000})
      if (rules_res.code === '20000') {
        vm.roleList  = rules_res.data.list
      }
      let treeMenu_res  = await getTreeMenu();
      if (treeMenu_res.code === '20000') {
        vm.TreeMenu = treeMenu_res.data;
      }
    },
    async getUserList() {
      const vm = this;
      vm.loading = true;
      let response = await getUserList(vm.query);
      vm.loading = false;
      if (response.code === '20000') {
        vm.total = response.data.total;
        vm.data = response.data.list;
      }
      
    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.query.pageNumber = val;
      this.getUserList()
    },
    search() {
      this.query.pageNumber = 1;
      this.getUserList()
    }
  }
}
</script>
<style lang="scss" scoped>
.adduser-model {
  width: 100%;
  overflow: hidden;
  position: relative;
  height: auto;
  .left-from-item {
    width: 50%;
    float: left;
    .box-body {
      margin-right: 30px;
    }
  }
  .right-from-item {
    position: absolute;
    left: 50%;
    right: 0;
    top: 0;
    bottom: 0;
    .right-from-box {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      left: 0;
      .select-rould-box {
        height: 100%;
        width: -webkit-calc(100% + 17px);
        width: -moz-calc(100% + 17px);
        width: calc(100% + 17px);
        overflow: auto;
        border: 1px solid #e4e7ed;
      }
    }
  }
}
// .select-rould-box {
//   // height: 390px;
//   position: absolute;
//   left: 50%;
//   right: 0;
//   top: 0;
//   bottom: 0;
//   overflow: scroll;
//   border: 1px solid #e4e7ed;
// }
</style>